//
//  ReadBookVOrH_VC+FloatBtns.m
//  KidReading
//
//  Created by telen on 16/3/8.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ReadBookVOrH_VC+FloatBtns.h"
#import "ConstDefine.h"
#import "MDRadialProgressView.h"
#import "MDRadialProgressTheme.h"

#define __timerDur (1/30.0) //telen 卡啦ok帧率
#define __CountSec (120)     //录音控制时长 秒
#define __CountSecEnd (9)  //录音倒计时时长 秒
#define __CountAnble (2)   //有效的录音时长 秒

@interface TLRecorderMp3_Reader : TLRecorderMp3
@property(nonatomic,strong)NSDate* createDate;//初始录音时间戳
@property(nonatomic,assign)NSInteger pageIndex;//录音页面
@property(nonatomic,assign)BOOL isRemindUnlogin;//是否提醒过，未登陆
@end
@implementation TLRecorderMp3_Reader
@end

@interface StatusButton_2_View_Rec : StatusButton_2_View
@property(nonatomic,readonly)CGFloat coutTime;
- (void)startRec;
- (void)stopRec;
@end
@implementation StatusButton_2_View_Rec
{
    NSTimer* timer;
    MDRadialProgressView* radialView;
    CGFloat coutTime;
}
@synthesize coutTime;
- (void)startRec
{
    [self stopRec];
    if (radialView == nil) {
        CGFloat w = self.width*1.1;
        MDRadialProgressTheme *newTheme = [[MDRadialProgressTheme alloc] init];
        newTheme.completedColor = [UIColor colorWithRed:126/255.0 green:143/255.0 blue:218/255.0 alpha:1];
        newTheme.incompletedColor = [UIColor clearColor];
        newTheme.centerColor = [UIColor colorWithRed:126/255.0 green:143/255.0 blue:218/255.0 alpha:0.3];
        newTheme.sliceDividerHidden = YES;
        newTheme.labelColor = [UIColor whiteColor];
        newTheme.labelShadowColor = [UIColor clearColor];
        newTheme.font = [UIFont boldSystemFontOfSize:w*0.3];
        newTheme.thickness = ceil(w*0.2);
        //
        CGRect frame = CGRectMake(0, 0, w, w);
        radialView =  [[MDRadialProgressView alloc] initWithFrame:frame andTheme:newTheme];
        radialView.center = self.contentCenter;
        radialView.progressTotal = __CountSecEnd;
        radialView.isShowCounter = YES;
        radialView.endString = @"";
    }
    //
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tick_CoutRec:) userInfo:nil repeats:YES];
    [timer fire];
}
- (void)stopRec
{
    if(timer)[timer invalidate],timer= nil;
    if (radialView.superview)[radialView removeFromSuperview];
    coutTime = 0;
}
- (void)tick_CoutRec:(NSTimer*)tmr
{
    [DataProcessing do_Main_quick:^{
        coutTime += tmr.timeInterval;
        NSInteger ct = __CountSec - coutTime;
        if (ct <= __CountSecEnd) {
            if (!radialView.superview) {
                radialView.userInteractionEnabled = NO;
                [self addSubview:radialView];
            }
            radialView.progressCounter = ct;
            if (ct <= 0) {
                [self setButtonStatus:NO];
                if(self.btnClicked)self.btnClicked(self);
                [self stopRec];
            }
        }
    }];
}
@end

#pragma mark-
@interface StatusButton_3_Sound: StatusButton_3_View
@property(nonatomic,strong)CAShapeLayer* circleShape;
@end
@implementation StatusButton_3_Sound
- (void)showSpeedCoverting:(BOOL)cing
{
    if (!self.circleShape) {
        UIColor* rippleColor = [UIColor colorWithRed:124/255.0 green:132/255.0 blue:197/255.0 alpha:0.9];
        UIView* view = self;
        UIView* ripplePathView = [[UIView alloc] initWithFrame:view.bounds];
        [ripplePathView.layer setCornerRadius:ripplePathView.bounds.size.width*0.5];
        
        UIColor *stroke = rippleColor ? rippleColor : [UIColor colorWithWhite:0.8 alpha:0.8];
        
        CGRect pathFrame = CGRectMake(-CGRectGetMidX(ripplePathView.bounds), -CGRectGetMidY(ripplePathView.bounds), ripplePathView.bounds.size.width, ripplePathView.bounds.size.height);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathFrame cornerRadius:ripplePathView.layer.cornerRadius];
        
        CGPoint shapePosition = CGPointMake(CGRectGetMidX(ripplePathView.bounds), CGRectGetMidY(ripplePathView.bounds));;
        
        CAShapeLayer *circleShape = [CAShapeLayer layer];
        circleShape.path = path.CGPath;
        circleShape.position = shapePosition;
        circleShape.fillColor = [UIColor clearColor].CGColor;
        circleShape.opacity = 0;
        circleShape.strokeColor = stroke.CGColor;
        circleShape.lineWidth = 2;
        [view.layer addSublayer:circleShape];
        circleShape.hidden = YES;
        self.circleShape = circleShape;
    }
    //
    if (cing) {
        if (self.circleShape.hidden) {
            self.circleShape.hidden = NO;
            //
            [CATransaction begin];
            //remove layer after animation completed
            [CATransaction setCompletionBlock:^{
                self.circleShape.hidden = YES;
            }];
            
            CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
            scaleAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
            scaleAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1)];
            
            CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
            alphaAnimation.fromValue = @1;
            alphaAnimation.toValue = @0;
            
            CAAnimationGroup *animation = [CAAnimationGroup animation];
            animation.animations = @[scaleAnimation, alphaAnimation];
            animation.duration = 2.f;
            animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
            [self.circleShape addAnimation:animation forKey:nil];
            
            [CATransaction commit];
        }
    }else{
        if (self.circleShape && self.circleShape.hidden == NO) {
            self.circleShape.hidden = YES;
        }
    }
}
@end


#pragma mark-
@interface ReadBookVOrH_VC()
@property(nonatomic,strong)FloatBtnView* fview;
@property(nonatomic,strong)StatusButton_2_View* fHomeBtn;
@property(nonatomic,strong)StatusButton_2_View* cnBtn;
@property(nonatomic,strong)StatusButton_2_View* enBtn;
@property(nonatomic,strong)StatusButton_2_View* pyBtn;
@property(nonatomic,strong)StatusButton_2_View* transBtn;
@property(nonatomic,strong)StatusButton_3_Sound* soundBtn;
@property(nonatomic,strong)StatusButton_2_View* soudSpeedBtn_1;
@property(nonatomic,strong)StatusButton_2_View* soudSpeedBtn_2;
@property(nonatomic,strong)StatusButton_2_View* soudSpeedBtn_3;

@property(nonatomic,strong)StatusButton_2_View_Rec* recordBtn;
@property(nonatomic,strong)StatusButton_2_View* playRecBtn;

@property(nonatomic,strong)StatusButton_2_View* ASRBtn;

@property(nonatomic,assign)NSInteger sreadIndexPage;
@property(nonatomic,strong)NSArray* SreadIndex;
@property(nonatomic,strong)StatusButton_2_View* currentSreadBtn;

@property(nonatomic,assign)BOOL hasHang;
@property(nonatomic,strong)TLRecorderMp3_Reader* recorder;
//
@property(nonatomic,assign)UIInterfaceOrientationMask yztRotation;
//
@property(nonatomic,strong)NSTimer* backPlayTimer;
@property(nonatomic,assign)BOOL isBackPlaying;
@property(nonatomic,assign)BOOL isFollowReadingDataOK;

@end

@implementation ReadBookVOrH_VC (FloatBtns)

ASSOCIATED(fview, setFview, FloatBtnView*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(fHomeBtn, setFHomeBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(cnBtn, setCnBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(enBtn, setEnBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(pyBtn, setPyBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(transBtn, setTransBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(soundBtn, setSoundBtn, StatusButton_3_Sound*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(soudSpeedBtn_1, setSoudSpeedBtn_1, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(soudSpeedBtn_2, setSoudSpeedBtn_2, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(soudSpeedBtn_3, setSoudSpeedBtn_3, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

ASSOCIATED_NSInteger(sreadIndexPage, setSreadIndexPage);
ASSOCIATED(SreadIndex, setSreadIndex, NSArray*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(currentSreadBtn, setCurrentSreadBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

ASSOCIATED(recordBtn, setRecordBtn, StatusButton_2_View_Rec*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(playRecBtn, setPlayRecBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

ASSOCIATED(ASRBtn, setASRBtn, StatusButton_2_View*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

ASSOCIATED_BOOL(hasHang, setHasHang);
ASSOCIATED(recorder, setRecorder, TLRecorderMp3_Reader*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

ASSOCIATED_NSInteger(yztRotation, setYztRotation);
//
ASSOCIATED(backPlayTimer, setBackPlayTimer, NSTimer*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED_BOOL(isBackPlaying, setIsBackPlaying);
ASSOCIATED_BOOL(isFollowReadingDataOK, setIsFollowReadingDataOK);
+ (void)load
{
    [self swizzleSelector:@selector(viewDidLoad) withSelector:@selector(viewDidLoad_floatBtns)];
    [self swizzleSelector:@selector(readViewBeganScroll) withSelector:@selector(readViewBeganScroll_floatBtns)];
    [self swizzleSelector:@selector(readViewBeganScroll_DragEnd) withSelector:@selector(readViewBeganScroll_DragEnd_floatBtns)];
    [self swizzleSelector:@selector(readViewDidScrolledTo:) withSelector:@selector(readViewDidScrolledTo_floatBtns:)];
    [self swizzleSelector:@selector(readViewSReadBtn:status:) withSelector:@selector(readViewSReadBtn_floatBtns:status:)];
    [self swizzleSelector:@selector(dealloc_My) withSelector:@selector(dealloc_floatBtns)];
    [self swizzleSelector:@selector(readViewDidLoadSuccess_PageView:) withSelector:@selector(readViewDidLoadSuccess_PageView_floatBtns:)];
    [self swizzleSelector:@selector(refreshData) withSelector:@selector(refreshData_floatBtns)];
    [self swizzleSelector:@selector(tapBack_floatBtns) withSelector:@selector(tapBack)];
    //
    [self swizzleSelector:@selector(applicationDidEnterBackground:) withSelector:@selector(applicationDidEnterBackground_floatBtns:)];
    [self swizzleSelector:@selector(applicationDidBecomeActive:) withSelector:@selector(applicationDidBecomeActive_floatBtns:)];
    //
    [self swizzleSelector:@selector(viewDidAppear:) withSelector:@selector(viewDidAppear_floatBtns:)];
    [self swizzleSelector:@selector(viewWillAppear:) withSelector:@selector(viewWillDisappear_floatBtns:)];
    //
    [self swizzleSelector:NSSelectorFromString(@"clickTopbarTitleBtn") withSelector:@selector(clickTopbarTitleBtn_floatBtns)];
}

- (void)tapBack_floatBtns
{
    //录音关闭
    if (self.recordBtn.onOff) {
        [self.recordBtn setButtonStatus:NO];
        [self clicked_recordBtn];
    }
    //
    [self tapBack_floatBtns];
}

- (void)viewDidLoad_floatBtns
{
    [self viewDidLoad_floatBtns];
    //
    //是否有 浮动挂签
    NSNumber* book_mark = self.bookDict[@"book_mark"];
    if (book_mark && [book_mark isEqualToNumber:@(-1)]) {
        self.hasHang = NO;
    }else{
        self.hasHang = YES;
    }
    TLRecorderMp3_Reader* recorder = [TLRecorderMp3_Reader new];
    self.recorder = recorder;
    //
    [self default_AudioCategory];
    //
    //NSTimer
    [self fireTick];
    //
#ifndef Pep_prj
    self.yztRotation = [WY3SDKLogin rotationTo];
    [WY3SDKLogin setRotationTo:self.rotation];
#endif
    //
    //刷新后台
    if(self.hasHang){
        [self start_backPlayTimer];
        [self refreshUI_backGround_Player];
    }
}

- (void)fireTick
{
    [timer invalidate];
    timer = [NSTimer scheduledTimerWithTimeInterval:__timerDur target:self selector:@selector(tick:) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)applicationDidEnterBackground_floatBtns:(UIApplication *)application
{
    [self applicationDidEnterBackground_floatBtns:application];
    //
    //设置后台播放  为我读
    if(self.hasHang){
        self.isBackPlaying = YES;
        [self start_backPlayTimer];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [self refreshUI_backGround_Player];
    }
    //
    if (self.soundBtn.status == StatusButton_3_View_Status_work) {
        [self.soundBtn setButtonStatus:StatusButton_3_View_Status_normal];
    }
    //
    if (!self.isAutoRead){
        [timer invalidate];
        [[TLSoundPlayer shareSingle] stopAllFiles];
    }
    [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
    //录音挂起
    if (self.recordBtn.onOff) {
        [self.recordBtn setButtonStatus:NO];
        [self clicked_recordBtn];
    }
    [self.playRecBtn setButtonStatus:NO];
    //
    //来电监听
    [self toListenner_Call];
}

- (void)applicationDidBecomeActive_floatBtns:(UIApplication *)application
{
    self.isBackPlaying = NO;
    [self applicationDidBecomeActive_floatBtns:application];
    //
    [self continueAutoRead:NO];
    [self fireTick];
}

- (void)default_AudioCategory
{
//    //系统键控制静音
//    //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
//    //播放声音互斥 其他应用
//    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
    
//    //扬声器播放 将关闭系统键控制静音
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    UInt32 category = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
    
//    //听筒播放 与 扬声器播放 互斥
//    //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
}

- (void)record_AudioCategory
{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    UInt32 category = kAudioSessionCategory_PlayAndRecord;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
}

- (void)dealloc_floatBtns
{
    [self dealloc_floatBtns];
    //
    [[TLSoundPlayer shareSingle] stopAllFiles_andClean];
    //
#ifndef Pep_prj
    [WY3SDKLogin setRotationTo:self.yztRotation];
#endif
    //
    [self.backPlayTimer invalidate];
}

- (void)refreshData_floatBtns
{
    [self refreshData_floatBtns];
    //
    [readView updateShowPageToIndex:self.currentIndex];
}

- (void)readViewDidLoadSuccess_PageView_floatBtns:(PageView *)pageView
{
    [self readViewDidLoadSuccess_PageView_floatBtns:pageView];
    //
    UserInfo* uinfo = [[CacheData shareSingle] getUserLoginInfo];
    if (self.hasHang) {
#ifndef Pep_prj
#ifndef YDYH_PJ
        [[NetSyncRecord shareSingle] downloadRecordWithUid:uinfo.uid BookId:self.bookid PageId:pageView.pageIndex completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            if (!error) {
                [self reflashFloatViewShow];
            }
        }];
#endif
#endif
    }
    [self reflashPageViewStatus];
    if (pageView == readView.currentPageView) {
        [self reflashFloatViewShow];
    }
}

- (void)readViewBeganScroll_floatBtns
{
    [self readViewBeganScroll_floatBtns];
    //
//    [self cleanStatusForCurrentSreadBtn];
//    self.SreadIndex = nil;
}

- (void)readViewBeganScroll_DragEnd_floatBtns
{
    [self readViewBeganScroll_DragEnd_floatBtns];
    //
    [self cleanStatusForCurrentSreadBtn];
    self.SreadIndex = nil;
    
    //拖动翻页后，取消下一页翻页
    [NSObject cancelPreviousPerformRequestsWithTarget:readView selector:@selector(nextPage) object:nil];
}


- (void)continueAutoRead:(BOOL)isTurnPage
{
#ifndef Pep_prj
#ifndef YDYH_PJ
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    if (self.isAutoRead_ForRec && self.isAutoRead && [[NetSyncRecord shareSingle] isExistRecordWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.currentIndex]) {
        NSString* filepath = [[NetSyncRecord shareSingle] getExitRecordFilePathWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.currentIndex];
        if(filepath && filepath.length >0)[[TLSoundPlayer shareSingle] rePlayFile:filepath andDelegate:self];
        else NSLog(@"ErrorRecordFile:%@",filepath);
    }
    if((isTurnPage && self.soundBtn.status != StatusButton_3_View_Status_forbit) || self.isAutoRead){
        if (!self.isAutoRead_ForRec  || ![[NetSyncRecord shareSingle] isExistRecordWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.currentIndex]) {
            if (mp3Arr.count > indexMp3) {
                NSString* mp3F = [mp3Arr objectAtIndex:indexMp3];
                mp3F = [self soudFileSpeedCheck:mp3F];
                mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
                AVAudioPlayer* player = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:mp3F];
                if (!(player && player.isPlaying)) {
                    [self playBookSound];
                }
            }
        }
    }
#endif
#endif
}

- (void)readViewDidScrolledTo_floatBtns:(PageView *)pageView
{
    [self readViewDidScrolledTo_floatBtns:pageView];
    //
    //
    if ([self.readSource isEqualToString:ReadSource_JR]) {
        if (self.currentIndex == 0
            || readView.currentPageView.pageType == BookPageType_pAccessibility
            || readView.currentPageView.pageType == BookPageType_pQuiz) {
            self.isAutoRead = NO;
            self.isAutoRead_ForRec = NO;
            self.needPageMap = YES;
            [self.soundBtn setButtonStatus:StatusButton_3_View_Status_forbit];
        }
        //
        //连续录音处理
        [self continueRecord_NewPage];
        [self.playRecBtn setButtonStatus:NO];
        //
        if(readView.goToPage_Action == NO)//句段篇支持
        {
            [[TLSoundPlayer shareSingle] stopAllFiles];
        }else if (self.SreadIndex == nil && !self.isAutoRead){
            self.SreadIndex = @[@(0)];//强制播完0句
        }
        
        if(self.soundBtn.status == StatusButton_3_View_Status_work)[self.soundBtn setButtonStatus:StatusButton_3_View_Status_normal];
        [self refalshMp3Arr];
        
        {//句段篇支持
            //更新 currentSreadBtn
            StatusButton_2_View* currentSreadBtn = [self msgTo_menthed:@"currentSreadBtn" refs:nil needReturnValue:YES];
            if (currentSreadBtn) {
                [currentSreadBtn setButtonStatus:NO];
                self.currentSreadBtn = nil;
                self.SreadIndex = nil;
                //
                NSInteger tag = currentSreadBtn.tag;
                if(tag == SreadBtn_TAG_Article || tag == SreadBtn_TAG_Paragraph)[readView.currentPageView enumerateSreadBtnUsingBlock:^(StatusButtonView * _Nonnull stsbtn, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSNumber* prev_suffix = stsbtn.userInfo[@"prev_suffix"];
                    if (stsbtn.tag == tag && prev_suffix && prev_suffix.boolValue) {
                        [self msgTo_menthed:@"setCurrentSreadBtn:" refs:@[stsbtn] needReturnValue:NO];
                        *stop = YES;
                    }
                }];
            }
            currentSreadBtn = [self msgTo_menthed:@"currentSreadBtn" refs:nil needReturnValue:YES];
            if (currentSreadBtn) {
                NSString* type = currentSreadBtn.userInfo[@"type"];
                //
                if (readView.currentPageView.paragraph_suffix
                    && (readView.currentPageView.paragraph_prev_suffix_index == nil || readView.currentPageView.paragraph_prev_suffix_index.count == 0)
                    && [type isEqualToString:@"paragraph"]) {
                    [readView performSelector:@selector(nextPage) withObject:nil afterDelay:2];
                }else if (readView.currentPageView.paragraph_prev_suffix_index.count > 0
                          && [type isEqualToString:@"paragraph"]) {
                    [self msgTo_menthed:@"setSreadIndex:" refs:@[readView.currentPageView.paragraph_prev_suffix_index] needReturnValue:NO];
                    indexMp3 = [readView.currentPageView.paragraph_prev_suffix_index[0] integerValue];
                    longx = 0;
                    NSNumber* isPlaying_n = [self msgTo_menthed:@"isPlaying_Mp3Index:" refs:@[@(indexMp3)] needReturnValue:YES];
                    if(readView.goToPage_Action == NO) if (!isPlaying_n || !isPlaying_n.boolValue) {
                        [DataProcessing do_Main_quick:^{
                            if(indexMp3 >= 0 && indexMp3 < mp3Arr.count)[self msgTo_menthed:@"playBookSound_Continue" refs:nil needReturnValue:NO];
                        }];
                    }
                    
                }
                //
                if (readView.currentPageView.article_suffix
                    && (readView.currentPageView.article_prev_suffix_index == nil  || readView.currentPageView.article_prev_suffix_index.count == 0)
                    && [type isEqualToString:@"article"]) {
                    [readView performSelector:@selector(nextPage) withObject:nil afterDelay:2];
                }else if (readView.currentPageView.article_prev_suffix_index.count > 0
                          && [type isEqualToString:@"article"]) {
                    [self msgTo_menthed:@"setSreadIndex:" refs:@[readView.currentPageView.article_prev_suffix_index] needReturnValue:NO];
                    indexMp3 = [readView.currentPageView.article_prev_suffix_index[0] integerValue];
                    longx = 0;
                    NSNumber* isPlaying_n = [self msgTo_menthed:@"isPlaying_Mp3Index:" refs:@[@(indexMp3)] needReturnValue:YES];
                    if(readView.goToPage_Action == NO)if (!isPlaying_n || !isPlaying_n.boolValue) {
                        [DataProcessing do_Main:^{
                            if(indexMp3 >= 0 && indexMp3 < mp3Arr.count)[self msgTo_menthed:@"playBookSound_Continue" refs:nil needReturnValue:NO];
                        } delay:0.1];
                    }
                    
                }
            }
            
            
            if (readView.goToPage_Action) {
                readView.goToPage_Action = NO;
                
                //句，句前跳后
                indexMp3 = readView.goPage.index;
                longx = 0;
                if(readView.goPage.type == GoToPageType_prev){
                    [DataProcessing do_Main:^{
                        if(indexMp3 >= 0 && indexMp3 < mp3Arr.count)[self msgTo_menthed:@"playBookSound_Continue" refs:nil needReturnValue:NO];
                    } delay:0.1];
                }
                
                //段篇，句后跳后
                if(currentSreadBtn && readView.goPage.type == GoToPageType_next){
                    indexMp3 = [self.SreadIndex[0] integerValue];
                    NSNumber* isPlaying_n = [self msgTo_menthed:@"isPlaying_Mp3Index:" refs:@[@(indexMp3)] needReturnValue:YES];
                    if (!isPlaying_n || !isPlaying_n.boolValue) {
                        [DataProcessing do_Main:^{
                            if(indexMp3 >= 0 && indexMp3 < mp3Arr.count)[self msgTo_menthed:@"playBookSound_Continue" refs:nil needReturnValue:NO];
                        } delay:0.1];
                    }
                }
            }
        }
        //
        [self continueAutoRead:YES];
        //
        [self checkNextPage_ForNoMp3];
        //
        [self reflashFloatViewShow];
        [self reflashPageViewStatus];
    }
    //
}

- (void)readViewSReadBtn_floatBtns:(StatusButton_2_View *)btn status:(BOOL)OnOff
{
    //[self readViewSReadBtn_floatBtns:btn status:OnOff];
    //
    //
    if (!OnOff) {
        [self indexMp3_Zero];
        [[TLSoundPlayer shareSingle] stopAllFiles];
        [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
        return;
    }
    if (btn.userInfo) {
        self.SreadIndex = [btn.userInfo objectForKey:@"index"];
        self.sreadIndexPage = readView.currentPageView.pageIndex;
        if ([self.SreadIndex isKindOfClass:[NSArray class]] && self.SreadIndex.count > 0) {
            [self.soundBtn setButtonStatus:StatusButton_3_View_Status_forbit];
            [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
            [[TLSoundPlayer shareSingle] stopAllFiles];
            indexMp3 = [self.SreadIndex[0] integerValue];
            self.currentSreadBtn = btn;
            if(indexMp3 >= 0 && indexMp3 < mp3Arr.count)[self playBookSound];
            else [self cleanStatusForCurrentSreadBtn];
        }else{
            self.SreadIndex = nil;
        }
    }else{
        [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
        [self cleanStatusForCurrentSreadBtn];
    }
}

#pragma mark-

- (void)addFloatView
{
#ifdef YDYH_PJ
    [NSObject msgToTarget:self menthed:@"addFloatView_ydyh" refs:nil needReturnValue:NO];
#endif
#ifndef CloseJRFloatView
    __weak ReadBookVOrH_VC* wself = self;
    if (!self.isAutoRead) {
        FloatBtnView* fview = [FloatBtnView floatBtnsWtihSuperView:self.view];
        self.fview = fview;
        fview.bookName = self.bookName;
        [self.view addSubview:fview];
        //
        CGRect frame = CGRectMake(0, 0, 10, 10);
        //
        StatusButton_2_View* fHomeBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_icon_floatbar_close.png" imageOff:@"book_icon_floatbar_open.png"];
        self.fHomeBtn = fHomeBtn;
        [fHomeBtn setButtonStatus:YES];
        fHomeBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_fHomeBtn];
        };
        //
        StatusButton_2_View* enBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_icon_en_display.png" imageOff:@"book_icon_en_hidden.png"];
        self.enBtn = enBtn;
        [enBtn setButtonStatus:YES];
        enBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_enBtn];
        };
        //
        StatusButton_2_View* cnBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_icon_cn_display.png" imageOff:@"book_icon_cn_hidden.png"];
        self.cnBtn = cnBtn;
        [cnBtn setButtonStatus:YES];
        cnBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_cnBtn];
        };
        //
        StatusButton_2_View* pyBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_icon_pinyin_display.png" imageOff:@"book_icon_pinyin_hidden.png"];
        self.pyBtn = pyBtn;
        [pyBtn setButtonStatus:YES];
        pyBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_pyBtn];
        };
        //
        StatusButton_2_View* transBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_icon_trans_highlight.png" imageOff:@"book_icon_trans_normal.png"];
        self.transBtn = transBtn;
        [transBtn setButtonStatus:NO];
        transBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_transBtn];
        };
        //录音相关按钮
        StatusButton_2_View_Rec* recordBtn = [[StatusButton_2_View_Rec alloc] initWithFrame:frame imageOn:nil imageOff:@"book_icon_record_one.png"];
        NSArray* arrAniRec = [NSArray arrayWithObjects:[UIImage imageNamed:@"book_icon_record_two.png"],[UIImage imageNamed:@"book_icon_record_one.png"],nil];
        [recordBtn setAni_UImageArr:arrAniRec ani_duration:1 forStatus:YES];
        self.recordBtn = recordBtn;
        [recordBtn setButtonStatus:NO];
        recordBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_recordBtn];
        };
        //
        StatusButton_2_View* playRecBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_icon_stop_pressed.png" imageOff:@"book_icon_play_normal.png"];
        self.playRecBtn = playRecBtn;
        [playRecBtn setButtonStatus:NO];
        playRecBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_playRecBtn];
        };
        [playRecBtn addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap_playRecBtn:)]];
        //
        //跟读
        if ([self isFollowReadingDataFilesOK]) {
            StatusButton_2_View* ASRBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"toolbar_btn_follow_speaking.png" imageOff:@"toolbar_btn_follow_speaking.png"];
            self.ASRBtn = ASRBtn;
            [ASRBtn setButtonStatus:NO];
            ASRBtn.btnClicked = ^(StatusButtonView* sBtn){
                [wself clicked_ASRBtn];
            };
        }
        //
        StatusButton_3_Sound* soundBtn = [[StatusButton_3_Sound alloc] initWithFrame:frame imageNormal:@"book_icon_speaker_pause.png" imageWork:@"" imageForbit:@"book_icon_speaker_stop.png"];
        NSArray* arrAni = [NSArray arrayWithObjects:[UIImage imageNamed:@"book_icon_speaker_play1.png"],[UIImage imageNamed:@"book_icon_speaker_play2.png"], nil];
        self.soundBtn = soundBtn;
        [soundBtn setAni_UImageArr:arrAni ani_duration:1 forStatus:StatusButton_3_View_Status_work];
        [soundBtn setButtonStatus:StatusButton_3_View_Status_forbit];
        soundBtn.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_soundBtn];
        };
        //
        StatusButton_2_View* soudSpeedBtn_1 = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_btn_speaker_speed_one_down.png" imageOff:@"book_btn_speaker_speed_one_noraml.png"];
        self.soudSpeedBtn_1 = soudSpeedBtn_1;
        [soudSpeedBtn_1 setButtonStatus:NO];
        soudSpeedBtn_1.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_soundBtn_1];
        };
        StatusButton_2_View*soudSpeedBtn_2 = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_btn_speaker_speed_two_down.png" imageOff:@"book_btn_speaker_speed_two_noraml.png"];
        self.soudSpeedBtn_2 = soudSpeedBtn_2;
        [soudSpeedBtn_2 setButtonStatus:YES];
        soudSpeedBtn_2.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_soundBtn_2];
        };
        StatusButton_2_View*soudSpeedBtn_3 = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"book_btn_speaker_speed_three_down.png" imageOff:@"book_btn_speaker_speed_three_noraml.png"];
        self.soudSpeedBtn_3 = soudSpeedBtn_3;
        [soudSpeedBtn_3 setButtonStatus:NO];
        soudSpeedBtn_3.btnClicked = ^(StatusButtonView* sBtn){
            [wself clicked_soundBtn_3];
        };
        //
        NSMutableArray* arr = [NSMutableArray arrayWithCapacity:0];
        if(enBtn)[arr addObject:enBtn];
        if(cnBtn)[arr addObject:cnBtn];
        if(pyBtn)[arr addObject:pyBtn];
        if(soundBtn)[arr addObject:soundBtn];
        if(transBtn)[arr addObject:transBtn];
        //
        CGFloat wh = 50/ratio_w;
        CGFloat min = 30;//telen 适配小分辨率
        wh = MAX(min, wh);
        //
        soudSpeedBtn_2.fbv_followPodValue = 40/ratio_w;
        soudSpeedBtn_1.fbv_followView = soundBtn;
        soudSpeedBtn_2.fbv_followView = soundBtn;
        soudSpeedBtn_3.fbv_followView = soundBtn;
        soudSpeedBtn_1.fbv_bool_KeepSizeValue = @(YES);
        soudSpeedBtn_2.fbv_bool_KeepSizeValue = @(YES);
        soudSpeedBtn_3.fbv_bool_KeepSizeValue = @(YES);
        soudSpeedBtn_1.fbv_followOffsetValue = [NSValue valueWithCGPoint:CGPointMake(-wh*0.666, -wh*0.73)];
        soudSpeedBtn_2.fbv_followOffsetValue = [NSValue valueWithCGPoint:CGPointMake(0, -wh*0.92)];
        soudSpeedBtn_3.fbv_followOffsetValue = [NSValue valueWithCGPoint:CGPointMake(wh*0.666, -wh*0.73)];
        soudSpeedBtn_1.frame = soudSpeedBtn_2.frame = soudSpeedBtn_3.frame = CGRectMake(0, 0, wh*0.66, wh*0.66);
        //
        fview.allBtnSize = CGSizeMake(wh, wh);
        frame = CGRectMake(0, 0, width_my, height_my);
        frame.size.height -= ceil(topBarHeight + pageMapView.mapHeigth);
        frame.size.width -= ceil(wh*0.5);
        frame.origin.y += ceil(topBarHeight);
        frame.origin.x += ceil(wh*0.25);
        fview.canBerthRect = frame;
        fview.ratio_w = ratio_w;
        [fview setHomeBtn:fHomeBtn andOtherFloatViews:arr];
        if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone && ![self isRotationHorizontal:self.rotation_to]) {
            fview.horizontal = YES;
            frame.size.height += ceil(topBarHeight*0.5);
            frame.origin.y -= ceil(topBarHeight*0.4);
        }
        floatframe_topBar = frame;
        fview.canBerthRect = floatframe_topBar;
        [fview doneSetting];
        //
        //
        frame.origin.y = 0;
        frame.size.height = self.view.bounds.size.height;
        if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone && ![self isRotationHorizontal:self.rotation_to]) {
            frame.origin.y += ceil(topBarHeight*0.15);
            frame.size.height -= ceil(topBarHeight*0.35);
        }
        floatframe_full = frame;
        //
        [self performSelector:@selector(reflashFloatViewShow) withObject:nil afterDelay:0.3f];
        
        //
        //transView.pt_unshowFollowView = transBtn;
        [NSObject msgToTarget:self getmenthed:@"transView" domenthed:@"setPt_unshowFollowView:" refs:@[self.transBtn] needReturnValue:NO];
    }
#endif
}

- (void)reflashFloatViewShow
{
    if (self.isAutoRead) {
        return;
    }
    UserInfo* uinfo = [[CacheData shareSingle] getUserLoginInfo];
    
    if(readView.currentPageView.pageType != BookPageType_pContent
       || readView.currentPageView.isDataDisplay == NO
       ){
        [self.fview unShow];
    }else{
        NSMutableArray* arr = [NSMutableArray arrayWithCapacity:0];
        if(self.transBtn && readView.currentPageView.hasTrans) [arr addObject:self.transBtn];
        if(self.enBtn && readView.currentPageView.hasEnglishWords && readView.currentPageView.bookType != 1) [arr addObject:self.enBtn];
        if(self.cnBtn && readView.currentPageView.hasChineseWords && readView.currentPageView.bookType != 0) [arr addObject:self.cnBtn];
        if(self.pyBtn && readView.currentPageView.hasPinyinWords) [arr addObject:self.pyBtn];
        //跟读按钮
        
        if (self.ASRBtn && readView.currentPageView.ASRTextArray.count > 0 && readView.currentPageView.mp3PathArray.count == readView.currentPageView.showTextArray.count && readView.currentPageView.ASRTextArray.count == readView.currentPageView.showTextArray.count && !self.recordBtn.onOff) {
            [arr addObject:self.ASRBtn];
        }
#ifndef Pep_prj
#ifndef YDYH_PJ
        //录音按钮组
        if (self.recordBtn && self.hasHang) {
            if (self.playRecBtn && !self.recordBtn.onOff && [[NetSyncRecord shareSingle] isExistRecordWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.currentIndex]) {
                [arr addObject:self.playRecBtn];
            }
            [arr addObject:self.recordBtn];
        }
#endif
#endif

        //
        if(self.soundBtn && readView.currentPageView.hasSounds && !self.recordBtn.onOff) [arr addObject:self.soundBtn];
        if(self.soudSpeedBtn_1 && self.soudSpeedBtn_2 && self.soudSpeedBtn_3
           && !self.recordBtn.onOff
           && self.soundBtn.status == StatusButton_3_View_Status_work
           && readView.currentPageView.hasSounds
           && readView.currentPageView.hasSounds_fast
           && readView.currentPageView.hasSounds_slower) [arr addObject:self.soudSpeedBtn_1],[arr addObject:self.soudSpeedBtn_2],[arr addObject:self.soudSpeedBtn_3];
        [self.fview reLayLoutFloatViews:arr];
        //
        [self.fview show];
    }
}

- (BOOL)isFollowReadingDataFilesOK
{
    if (self.isFollowReadingDataOK) return self.isFollowReadingDataOK;
    NSString* fPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"asr.dat"];
    self.isFollowReadingDataOK = [[NSFileManager defaultManager] fileExistsAtPath:fPath];
    //
    return self.isFollowReadingDataOK;
}


- (void)reflashPageViewStatus
{
    if(self.enBtn)[readView updatePagesEnglishToShow:self.enBtn.onOff];
    if(self.cnBtn)[readView updatePagesChineseToShow:self.cnBtn.onOff];
    if(self.pyBtn)[readView updatePagesPinyinToShow:self.pyBtn.onOff];
    if (self.isAutoRead || self.recordBtn.onOff) {
        [readView updatePagesSreadBtnToShow:NO];
    }else{
        [readView updatePagesSreadBtnToShow:YES];
    }
}

- (void)cleanStatusForCurrentSreadBtn
{
    if (self.currentSreadBtn) {
        [self.currentSreadBtn setButtonStatus:NO];
        self.currentSreadBtn = nil;
    }
}

- (void)changeSpeedToButton:(StatusButton_2_View*)sbview
{
#ifndef Pep_prj
#ifndef YDYH_PJ
    NSString* mode = RMode_normal;
    BOOL needReplay = sbview.onOff;
    [sbview setButtonStatus:!sbview.onOff];
    StatusButton_3_View_Status speed = StatusButton_3_View_Status_normal;
    if (sbview == self.soudSpeedBtn_1) {
        [self.soudSpeedBtn_1 setButtonStatus:YES];
        [self.soudSpeedBtn_2 setButtonStatus:NO];
        [self.soudSpeedBtn_3 setButtonStatus:NO];
        speed = StatusButton_3_View_Status_slower;
        mode = RMode_slow;
    }else if (sbview == self.soudSpeedBtn_3) {
        [self.soudSpeedBtn_3 setButtonStatus:YES];
        [self.soudSpeedBtn_2 setButtonStatus:NO];
        [self.soudSpeedBtn_1 setButtonStatus:NO];
        speed = StatusButton_3_View_Status_fast;
        mode = RMode_fast;
    }else if (sbview == self.soudSpeedBtn_2) {
        [self.soudSpeedBtn_2 setButtonStatus:YES];
        [self.soudSpeedBtn_1 setButtonStatus:NO];
        [self.soudSpeedBtn_3 setButtonStatus:NO];
    }
    if (needReplay) {
        [self cleanStatusForCurrentSreadBtn];
        self.SreadIndex = nil;
        [self indexMp3_Zero];
        [self playBookSound_Continue];
    }
    //
    if (readView.currentPageView.pageType == BookPageType_pContent) {
        NSInteger index = [[pageDisArr objectAtIndex:self.currentIndex] integerValue];
        [[DBHelper shareInstance] addReadInfo_pageOperation:self.bookid pageIndex:index type:RType_speed mode:mode];
    }
#endif
#endif
}

- (NSString*)soudFileSpeedCheck:(NSString*)mp3F
{
    if (self.soudSpeedBtn_1.onOff) {
        if (readView.currentPageView.hasSounds_fast) {
            mp3F = [DataProcessing getSlowerSoudFilePathFromPath:mp3F];
        }else{
            [self changeSpeedToButton:self.soudSpeedBtn_2];
        }
    }
    else if (self.soudSpeedBtn_3.onOff) {
        if (readView.currentPageView.hasSounds_fast) {
            mp3F = [DataProcessing getFastSoudFilePathFromPath:mp3F];
        }else{
            [self changeSpeedToButton:self.soudSpeedBtn_2];
        }
    }
    return mp3F;
}

- (NSNumber*)isPlaying_Mp3Index:(NSNumber*)index_p
{
    if (index_p) {
        NSInteger index = index_p.integerValue;
        if (mp3Arr.count > index && index >= 0) {
            NSString* mp3F = [mp3Arr objectAtIndex:index];
            mp3F = [self soudFileSpeedCheck:mp3F];
            mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
            return @([[TLSoundPlayer shareSingle] isFilePlaying:mp3F]);
        }
    }
    return @(NO);
}

- (void)playBookSound
{
    BOOL ret = !self.isAutoRead && (self.soundBtn.status == StatusButton_3_View_Status_forbit || readView.currentPageView.pageType == BookPageType_pForeCover);
    if (self.SreadIndex && self.SreadIndex.count > 0) {
        ret = NO;
    }
    if (ret) {
        return;
    }
    if (mp3Arr.count > indexMp3) {
        NSString* mp3F = [mp3Arr objectAtIndex:indexMp3];
        mp3F = [self soudFileSpeedCheck:mp3F];
        mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
        BOOL playSucess = [[TLSoundPlayer shareSingle] rePlayFile:mp3F andDelegate:self];
        if (!playSucess) {
            NSLog(@"播放失败！%@",mp3F);
            [DataProcessing do_Main_quick:^{
                [[TLSoundPlayer shareSingle] rePlayFile:mp3F andDelegate:self];
            }];
        }
    }
}

- (void)playBookSound_Continue
{
    if (mp3Arr.count > indexMp3) {
        [[TLSoundPlayer shareSingle] stopAllFiles];
        [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
        NSString* mp3F = [mp3Arr objectAtIndex:indexMp3];
        mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
        mp3F = [self soudFileSpeedCheck:mp3F];
        NSTimeInterval time = longx;
        if (self.soudSpeedBtn_3.onOff) {
            time *= ceil(100000.0/(100+[DataProcessing shareSingle].soundPlayRatio_fast))/1000.0;
        }
        else if (self.soudSpeedBtn_1.onOff) {
            time *= ceil(100000.0/(100+[DataProcessing shareSingle].soundPlayRatio_slower))/1000.0;
        }
        //[[TLSoundPlayer shareSingle] playFile:mp3F fromTime:time andDelegate:self];
        BOOL playSucess = [[TLSoundPlayer shareSingle] rePlayFile:mp3F andDelegate:self];
        if (!playSucess) {
            NSLog(@"播放失败！%@",mp3F);
            [DataProcessing do_Main_quick:^{
                [[TLSoundPlayer shareSingle] rePlayFile:mp3F andDelegate:self];
            }];
        }
    }
}

- (void)autoReaderIF
{
    [self checkNextPage_ForNoMp3];
    if (self.isAutoRead && mp3Arr.count >0 && readView.currentPageView.pageType == BookPageType_pForeCover){
        [self performSelector:@selector(playBookSound) withObject:nil afterDelay:0.6];
    }
}

- (void)checkNextPage_ForNoMp3
{
    if (self.isAutoRead) {
#ifndef Pep_prj
#ifndef YDYH_PJ
        UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        [NSObject cancelPreviousPerformRequestsWithTarget:readView selector:@selector(nextPage) object:nil];
        if (!mp3Arr || mp3Arr.count == 0) {
            if (!self.isAutoRead_ForRec  || ![[NetSyncRecord shareSingle] isExistRecordWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.currentIndex]) {
                if (self.isBackPlaying) {
                    [readView performSelector:@selector(nextPage) withObject:nil afterDelay:0.01];
                }else{
                    [readView performSelector:@selector(nextPage) withObject:nil afterDelay:2];
                }
            }
        }
#endif
#endif
    }
}

- (void)indexMp3_Zero
{
    indexMp3 = 0;
    if ([readView.currentPageView prevGo:0] != nil && mp3Arr.count > 1) {
        indexMp3 = 1;
    }
}

- (void)refalshMp3Arr
{
    mp3Arr = [readView.currentPageView getMp3Arr];
    [self indexMp3_Zero];
}

#define tickStop 60
- (void)tick:(NSTimer*)tmr
{
    dispatch_async(dispatch_get_main_queue(), ^{
        //
        static int tick_delay = 0;
        if (mp3Arr.count > indexMp3) {
            NSString* mp3F = [mp3Arr objectAtIndex:indexMp3];
            mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
            mp3F = [self soudFileSpeedCheck:mp3F];
            if ([[TLSoundPlayer shareSingle] isFilePlaying:mp3F]) {
                longx = [[TLSoundPlayer shareSingle] getPlayProgressForFile:mp3F];
                if (self.soudSpeedBtn_3.onOff) {
                    longx /= ceil(100000.0/(100+[DataProcessing shareSingle].soundPlayRatio_fast))/1000.0;
                }
                else if (self.soudSpeedBtn_1.onOff) {
                    longx /= ceil(100000.0/(100+[DataProcessing shareSingle].soundPlayRatio_slower))/1000.0;
                }
                [readView.currentPageView update_KOK_toPlayMSecond:longx andSentenceIndex:indexMp3];
                if(self.SreadIndex == nil)[self.soundBtn setButtonStatus:StatusButton_3_View_Status_work];
                tick_delay = 0;
            }else if(self.soundBtn.status == StatusButton_3_View_Status_work){
                [self.soundBtn setButtonStatus:StatusButton_3_View_Status_normal];
                tick_delay++;
                if(tick_delay > tickStop){
                    longx = 0;
                    indexMp3 = mp3Arr.count;
                    tick_delay = 0;
                }
            }else if(self.soundBtn.status == StatusButton_3_View_Status_forbit && !self.isAutoRead){
                tick_delay++;
                if(tick_delay > tickStop){
                    longx = 0;
                    indexMp3 = mp3Arr.count;
                    tick_delay = 0;
                }
            }
            //NSLog(@"page %@ ---- mp3 %@",@(readView.currentPageView.pageIndex),@(indexMp3));
        }
        //
        //
        [self.soundBtn showSpeedCoverting:!(readView.currentPageView.hasSounds && readView.currentPageView.hasSounds_fast && readView.currentPageView.hasSounds_slower)];
    });
}
#pragma mark-

- (void)playMyRecord
{
    self.isAutoRead = YES;
    self.isAutoRead_ForRec = YES;
    [self indexMp3_Zero];
    [NSObject msgToTarget:self menthed:@"autoReaderIF" refs:nil needReturnValue:NO];
}

- (void)startRecord
{
#ifndef Pep_prj
#ifndef YDYH_PJ
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSDate* date = [NSDate date];
    long long time = [DataProcessing timestampFromNSDate:date];
    self.recorder.createDate = date;
    self.recorder.pageIndex = self.currentIndex;
    self.recorder.filePath = [[NetSyncRecord shareSingle] getRecordStorePathWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.recorder.pageIndex RecordTime:time];
    [self record_AudioCategory];
    [DataProcessing do_Main_quick:^{
        BOOL ret = [self.recorder start];
        if (ret) {
            [self.recordBtn startRec];
        }else{
            [self.recordBtn setButtonStatus:NO];
            [self reflashFloatViewShow];
        }
        [UIApplication sharedApplication].idleTimerDisabled = YES;//防止锁屏
        [readView updatePagesSreadBtnToShow:NO];//关闭sread
    }];
    //
    [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
#endif
#endif
}

- (void)stopRecord
{
#ifndef Pep_prj
#ifndef YDYH_PJ
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [self.recorder stop];
    [self default_AudioCategory];
    CGFloat coutTime = self.recordBtn.coutTime;
    [DataProcessing do_Async_quick:^{
        if (coutTime <= __CountAnble || [DataProcessing getFileSize_MB:self.recorder.filePath] <= 0) {
            [[NetSyncRecord shareSingle] deleteRubbishRecordWithKeyPath:self.recorder.filePath];
        }else{
            NSDate* date = self.recorder.createDate;
            long long time = [DataProcessing timestampFromNSDate:date];
            [[NetSyncRecord shareSingle] uploadRecordWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.recorder.pageIndex RecordTime:time Success:nil Failure:nil];
        }
        [self.recordBtn stopRec];
    }];
    [UIApplication sharedApplication].idleTimerDisabled = NO;//关闭防止锁屏
    [readView updatePagesSreadBtnToShow:YES];//恢复sread
#endif
#endif
}

- (void)continueRecord_NewPage
{
#ifndef Pep_prj
#ifndef YDYH_PJ
    if (self.recordBtn.onOff) {
        UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        [self.soundBtn setButtonStatus:StatusButton_3_View_Status_forbit];
        //
        if(readView.currentPageView.pageType == BookPageType_pContent){
            //[DataProcessing do_Async_quick:^{
                if (self.recordBtn.coutTime <= __CountAnble || [DataProcessing getFileSize_MB:self.recorder.filePath] <= 0) {
                    [[NetSyncRecord shareSingle] deleteRubbishRecordWithKeyPath:self.recorder.filePath];
                }else{
                    NSDate* date = self.recorder.createDate;
                    long long time = [DataProcessing timestampFromNSDate:date];
                    [[NetSyncRecord shareSingle] uploadRecordWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.recorder.pageIndex RecordTime:time Success:nil Failure:nil];
                }
                //
                NSDate* date = [NSDate date];
                long long time = [DataProcessing timestampFromNSDate:date];
                self.recorder.createDate = date;
                self.recorder.pageIndex = self.currentIndex;
                NSString* filePath = [[NetSyncRecord shareSingle] getRecordStorePathWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.recorder.pageIndex RecordTime:time];
                [self.recorder continueRecordToNewFilePath:filePath];
                [self.recordBtn startRec];
            //}];
            [readView updatePagesSreadBtnToShow:NO];//关闭sread
        }else{
            [self stopRecord];
            [self.recordBtn setButtonStatus:NO];
            [readView updatePagesSreadBtnToShow:YES];//恢复sread
        }
    }
#endif
#endif
}

#pragma mark-
- (void)clicked_fHomeBtn
{
    //telen 统计
//    if(self.fHomeBtn.onOff)[UMSAgent postEvent:@"Toolbar_unfold" label:self.bookName];
//    else [UMSAgent postEvent:@"Toolbar_fold" label:self.bookName];
    //statistical统计
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"功能按钮（浮动）"] needReturnValue:NO];
}

- (void)clicked_cnBtn
{
    [self reflashPageViewStatus];
    //telen 统计
//    if(self.cnBtn.onOff)[UMSAgent postEvent:@"Toolbar_cn_on" label:self.bookName];
//    else [UMSAgent postEvent:@"Toolbar_cn_off" label:self.bookName];
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"中文隐藏"] needReturnValue:NO];
}

- (void)clicked_enBtn
{
    [self reflashPageViewStatus];
    //telen 统计
//    if(self.enBtn.onOff)[UMSAgent postEvent:@"Toolbar_en_on" label:self.bookName];
//    else [UMSAgent postEvent:@"Toolbar_en_off" label:self.bookName];
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"英文隐藏"] needReturnValue:NO];
}

- (void)clicked_pyBtn
{
    [self reflashPageViewStatus];
    //telen 统计
//    if(self.pyBtn.onOff)[UMSAgent postEvent:@"Toolbar_py_on" label:self.bookName];
//    else [UMSAgent postEvent:@"Toolbar_py_off" label:self.bookName];
    [NSObject msgToTarget:self menthed:@"statistical_pinyin" refs:nil needReturnValue:NO];
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"拼音隐藏"] needReturnValue:NO];
}

- (void)clicked_transBtn
{
    TransView* transView = [NSObject msgToTarget:self menthed:@"transView" refs:nil needReturnValue:YES];
    NSNumber* isTransViewWorking = [NSObject msgToTarget:self menthed:@"isTransViewWorking" refs:nil needReturnValue:YES];
    if (!transView.isInShowing) {
        if (self.transBtn.onOff) {
            [transView setText:readView.currentPageView.getTrans];
            transView.pt_unshowFollowView = self.transBtn;
            if (!isTransViewWorking) {
                [transView show];
            }
        }else{
            [transView unShow];
        }
    }else{
        [self.transBtn setButtonStatus:!self.transBtn.onOff];
    }
    //telen 统计
    //[UMSAgent postEvent:@"Toolbar_trans_clk" label:self.bookName];
#ifndef WHY_PJ
#ifndef Pep_prj
    //阅读统计
    if (readView.currentPageView.pageType == BookPageType_pContent) {
        NSInteger index = [[pageDisArr objectAtIndex:self.currentIndex] integerValue];
        [[DBHelper shareInstance] addReadInfo_pageOperation:self.bookid pageIndex:index type:RType_trans mode:@""];
    }
#endif
#endif
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"翻译"] needReturnValue:NO];
}

- (void)clicked_recordBtn
{
    if (self.recordBtn.onOff) {
        [self.playRecBtn setButtonStatus:NO];
        [[TLSoundPlayer shareSingle] stopAllFiles];
        //UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        //麦克风判断
        int micState = [TLRecorderMp3 canMicrophone];
        if (micState == -1) {
            [self performSelector:@selector(clicked_recordBtn) withObject:nil afterDelay:0.1];
            return;
        }
        //
        if (micState == 0) {
            //
            [self.recordBtn setButtonStatus:NO];
            [UIAlertView tl_showTitle:@"" message:ReadLocalizedString(@"msgRecSetting") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
                if(buttonIndex == 1){
                    if ([[UIDevice currentDevice].systemVersion floatValue] < 8) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=MICROPHONE"]];
                    }else{
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                    }
                }
            } buttonTitles:ReadLocalizedString(@"cancel"),ReadLocalizedString(@"settings"),nil];
        }
        if(micState == 1){
//            //登录判断
//            if (!self.recorder.isRemindUnlogin && uinfo.isGuest_exp_device) {
//                [self.recordBtn setButtonStatus:NO];
//                self.recorder.isRemindUnlogin = YES;
//                [UIAlertView tl_showTitle:@"" message:ReadLocalizedString(@"msgLoginRec") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
//                    if (buttonIndex == 0) {
//                        [self startRecord];
//                        [self.recordBtn setButtonStatus:YES];
//                        [self reflashFloatViewShow];
//                    }else if(buttonIndex == 1){
//                        [[RootViewController shareLastInstance] yzt_Login:NO formVC:self];
//                    }
//                } buttonTitles:ReadLocalizedString(@"recToRead"),ReadLocalizedString(@"singIn"),nil];
//            }else{
                [self startRecord];
                [self reflashFloatViewShow];
//            }
        }
    }else{
        [self stopRecord];
        [DataProcessing do_Main:^{
            [self reflashFloatViewShow];
        } delay:0.1];
    }
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"录音按钮"] needReturnValue:NO];
}

- (void)clicked_playRecBtn
{
#ifndef Pep_prj
#ifndef YDYH_PJ
    [[TLSoundPlayer shareSingle] stopAllFiles];
    [self.soundBtn setButtonStatus:StatusButton_3_View_Status_forbit];
    //
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSString* filepath = [[NetSyncRecord shareSingle] getExitRecordFilePathWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.currentIndex];
    if (self.playRecBtn.onOff) {
        if (filepath && filepath.length > 0) {
            [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
            BOOL ret = [[TLSoundPlayer shareSingle] rePlayFile:filepath andDelegate:self];
            if (!ret)[self.playRecBtn setButtonStatus:NO];
        }else{
            [self.playRecBtn setButtonStatus:NO];
        }
    }
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"录音播放"] needReturnValue:NO];
#endif
#endif
}

- (void)longTap_playRecBtn:(UILongPressGestureRecognizer*)longtap

{
#ifndef Pep_prj
#ifndef YDYH_PJ
    if (longtap.state == UIGestureRecognizerStateBegan) {
        [UIAlertView tl_showTitle:@"" message:NSLocalizedString(@"msgRealDelRecord", nil) didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
                [[TLSoundPlayer shareSingle] stopAllFiles];
                [[NetSyncRecord shareSingle] deletePageRecordWithUid:uinfo.uid BookId:self.bookid PageId:self.currentIndex];
                [self reflashFloatViewShow];
            }
        } buttonTitles:NSLocalizedString(@"cancel", nil),NSLocalizedString(@"sure", nil),nil];
    }
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"录音删除"] needReturnValue:NO];
#endif
#endif
}

- (void)clicked_ASRBtn{
#ifndef Pep_prj
#ifndef YDYH_PJ
    FollowReadingViewController* followReadingVC = [[FollowReadingViewController alloc] init];
    if (self.evaluateDict.count > 0) {
        followReadingVC.isUseCutWord = NO;
    }else{
        followReadingVC.isUseCutWord = YES;
    }
    followReadingVC.bookId = self.bookid;
    followReadingVC.pageId = readView.currentPageView.pageIndex + 1;
    followReadingVC.showTextArray = readView.currentPageView.showTextArray;
    followReadingVC.ASRTextArray = readView.currentPageView.ASRTextArray;
    followReadingVC.textLangArray = readView.currentPageView.textLangArray;
    followReadingVC.mp3Array = readView.currentPageView.mp3PathArray;
    followReadingVC.rotation_to = self.rotation_to;
    //清除之前的音频 恢复按钮状态
    [[TLSoundPlayer shareSingle] stopAllFiles_andClean];
    [self.soundBtn setButtonStatus:StatusButton_3_View_Status_forbit];
    [self.playRecBtn setButtonStatus:NO];
    [readView.currentPageView stopSreadBtns];
    [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
    indexMp3 = mp3Arr.count;
    //
    [self presentViewController:followReadingVC animated:YES completion:nil];
    //统计
    NSInteger index = [[pageDisArr objectAtIndex:self.currentIndex] integerValue];
    [[DBHelper shareInstance] addReadInfo_pageOperation:self.bookid pageIndex:index type:RType_followRead mode:@""];
#endif
#endif
}

- (void)clicked_soundBtn
{
    StatusButton_3_View* soundBtn = self.soundBtn;
    switch (soundBtn.status) {
        case StatusButton_3_View_Status_normal:
        {
            [self cleanStatusForCurrentSreadBtn];
            [self indexMp3_Zero];
            [soundBtn setButtonStatus:StatusButton_3_View_Status_work];
            [[TLSoundPlayer shareSingle] stopAllFiles];
            self.SreadIndex = nil;
            [self playBookSound];
        }
            break;
        case StatusButton_3_View_Status_work:
        {
            [soundBtn setButtonStatus:StatusButton_3_View_Status_forbit];
            [[TLSoundPlayer shareSingle] stopAllFiles];
            [self indexMp3_Zero];
            [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
            [self cleanStatusForCurrentSreadBtn];
            [self indexMp3_Zero];
        }
            break;
        case StatusButton_3_View_Status_forbit:
        {
            [self cleanStatusForCurrentSreadBtn];
            [[TLSoundPlayer shareSingle] stopAllFiles];
            [self indexMp3_Zero];
            [soundBtn setButtonStatus:StatusButton_3_View_Status_work];
            self.SreadIndex = nil;
            [self playBookSound];
        }
            break;
        default:
            break;
    }
    //录音播放结束
    if(self.playRecBtn.onOff)[self.playRecBtn setButtonStatus:NO];
    //
    [self reflashFloatViewShow];
    //telen 统计
    if (soundBtn.status == StatusButton_3_View_Status_work) {
        //[UMSAgent postEvent:@"Toolbar_read_pause" label:self.bookName];
        [NSObject msgToTarget:self menthed:@"statistical_play" refs:nil needReturnValue:NO];
        //[self statistical_play];
    }
    if (soundBtn.status == StatusButton_3_View_Status_forbit) {
        //[UMSAgent postEvent:@"Toolbar_read_off" label:self.bookName];
    }
    //
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"播放按钮"] needReturnValue:NO];
}

- (void)clicked_soundBtn_1
{
    [self changeSpeedToButton:self.soudSpeedBtn_1];
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"播放调速_1"] needReturnValue:NO];
}

- (void)clicked_soundBtn_2
{
    [self changeSpeedToButton:self.soudSpeedBtn_2];
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"播放调速_2"] needReturnValue:NO];
}

- (void)clicked_soundBtn_3
{
    [self changeSpeedToButton:self.soudSpeedBtn_3];
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"播放调速_3"] needReturnValue:NO];
}

- (BOOL)isMp3ForLastParagraph:(NSInteger)mp3Index
{
    __block StatusButtonView* sbtn = nil;
    [readView.currentPageView enumerateSreadBtnUsingBlock:^(StatusButtonView * _Nonnull stsbtn, NSUInteger idx, BOOL * _Nonnull stop) {
        if (stsbtn.tag == SreadBtn_TAG_Paragraph) {
            sbtn = stsbtn;
        }
    }];
    if (sbtn) {
        NSArray *arr = sbtn.userInfo[@"index"];
        for (NSNumber* num in arr) {
            if (num.integerValue == mp3Index) {
                return YES;
            }
        }
    }
    return NO;
}

- (void)tlSoundPlayerDidFinishPlayingFile:(NSString *)fileFullPath
{
    //声音停止时候，诊断翻页完成情况，补充翻页加载数据
    [readView checkPageScroll];
    
    //修补句翻页，页未加载完成的问题
    if (readView.goToPage_Action) {
        [DataProcessing do_Main:^{
            [self tlSoundPlayerDidFinishPlayingFile_:fileFullPath];
        } delay:0.3];//等待新页加载完成
    }else{
        [self tlSoundPlayerDidFinishPlayingFile_:fileFullPath];
    }
}
- (void)tlSoundPlayerDidFinishPlayingFile_:(NSString *)fileFullPath
{
    //确保播放已经停止
    [[TLSoundPlayer shareSingle] stopFilePlay:fileFullPath];
    //
    static NSString* SynPlayEnd = @"tlSoundPlayerDidFinishPlayingFile_:";
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    @synchronized (SynPlayEnd) {
#ifndef Pep_prj
        if ([self.readSource isEqualToString:ReadSource_JR]) {
            if (self.SreadIndex && self.SreadIndex.count > 0) {
                for (int i=0; i<self.SreadIndex.count; i++) {
                    if ([self.SreadIndex[i] integerValue] == indexMp3) {
                        if (i+1 < self.SreadIndex.count) {
                            //音频停止的时候，尝试完成卡拉OK
                            [readView.currentPageView update_KOK_toPlayMSecond:9999999 andSentenceIndex:indexMp3];
                            
                            indexMp3 = [self.SreadIndex[i+1] integerValue];
                            [self playBookSound];
                            break;
                        }else{
                            NSString* type = self.currentSreadBtn.userInfo[@"type"];
                            NSNumber* paragraph_suffix = self.currentSreadBtn.userInfo[@"paragraph_suffix"];
                            NSNumber* article_suffix = self.currentSreadBtn.userInfo[@"article_suffix"];
                            BOOL nextpage = NO;
                            if (paragraph_suffix != nil
                                && (readView.currentPageView.pageIndex ==self.sreadIndexPage || [self isMp3ForLastParagraph:indexMp3])
                                && readView.currentPageView.paragraph_suffix
                                && [type isEqualToString:@"paragraph"]) {
                                [readView performSelector:@selector(nextPage) withObject:nil afterDelay:0.001];
                                nextpage = YES;
                            }
                            //减去最后一句的判断，去完善 currentSreadBtn 更新逻辑
                            if (article_suffix != nil && readView.currentPageView.article_suffix &&[type isEqualToString:@"article"]) {
                                [readView performSelector:@selector(nextPage) withObject:nil afterDelay:0.001];
                                nextpage = YES;
                            }
                            self.SreadIndex = nil;
                            if (!nextpage)[self cleanStatusForCurrentSreadBtn];
                            //
                            [self.currentSreadBtn setButtonStatus:NO];
                            [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
                            [self indexMp3_Zero];
                        }
                    }
                }
            }else{
#ifndef YDYH_PJ
                if (self.isAutoRead && self.isAutoRead_ForRec && [[NetSyncRecord shareSingle] isExistRecordWithUid:uinfo.uid BookId:self.bookid CurrentPage:self.currentIndex]) {
                    [readView performSelector:@selector(nextPage) withObject:nil afterDelay:1];
                }else
#endif
                {
                    if (mp3Arr.count-1 > indexMp3) {
                        //音频停止的时候，尝试完成卡拉OK
                        [readView.currentPageView update_KOK_toPlayMSecond:9999999 andSentenceIndex:indexMp3];
                        //
                        indexMp3++;
                        [self playBookSound];
                    }else if (mp3Arr.count-1 <= indexMp3) {
                        //音频停止的时候，尝试完成卡拉OK
                        [readView.currentPageView update_KOK_toPlayMSecond:9999999 andSentenceIndex:indexMp3];
                        //
                        [self indexMp3_Zero];
                        if (self.isAutoRead) {
                            [readView performSelector:@selector(nextPage) withObject:nil afterDelay:1];
                        }else{
                            if(self.soundBtn.status != StatusButton_3_View_Status_forbit)[self.soundBtn setButtonStatus:StatusButton_3_View_Status_normal];
                            [DataProcess do_Main_quick:^{
                                [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
                            }];
                            //[self reflashFloatViewShow];
                            [NSObject msgToTarget:self menthed:@"reflashFloatViewShow" refs:nil needReturnValue:NO];
                        }
                        if (mp3Arr.count-1 < indexMp3) {
                            NSLog(@"Error_Mp3Index: %s Mp3Arr:%@(index:%@)",__FUNCTION__,mp3Arr,@(indexMp3));
                        }
                    }
                }
            }
            //录音播放结束
            if(self.playRecBtn.onOff)[self.playRecBtn setButtonStatus:NO];
        }
#endif
    }
    
    if ([self.readSource isEqualToString:ReadSource_Pep]) {
        NSString* type = self.currentSreadBtn.userInfo[@"type"];
        if (self.SreadIndex && self.SreadIndex.count > 0) {
            for (int i=0; i<self.SreadIndex.count; i++) {
                if ([self.SreadIndex[i] integerValue] == indexMp3) {
                    if (i+1 < self.SreadIndex.count) {
                        indexMp3 = [self.SreadIndex[i+1] integerValue];
                        [self playBookSound];
                        break;
                    }
//                    else if(mp3Arr.count-1 > indexMp3){
//                        [self cleanStatusForCurrentSreadBtn];
//                        self.SreadIndex = nil;
//                        [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
//                    }
                    else{
                        if (readView.currentPageView.pageIndex ==self.sreadIndexPage && readView.currentPageView.paragraph_suffix && [type isEqualToString:@"paragraph"]) {
                            [readView performSelector:@selector(nextPage) withObject:nil afterDelay:0.001];
                        }
                        if (mp3Arr.count-1 <= indexMp3 && readView.currentPageView.article_suffix &&[type isEqualToString:@"article"]) {
                            [readView performSelector:@selector(nextPage) withObject:nil afterDelay:0.001];
                        }
                        //
                        [self.currentSreadBtn setButtonStatus:NO];
                        [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
                        [self indexMp3_Zero];
                        self.SreadIndex = nil;
                    }
                }
            }
        }else{
            [self cleanStatusForCurrentSreadBtn];
            self.SreadIndex = nil;
            [readView.currentPageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
        }
    }
}

#pragma mark- 为我读/自己读 切换
- (void)clickTopbarTitleBtn_floatBtns
{
    if (!self.isAutoRead && mp3Arr.count > indexMp3) {
        NSString* mp3F = [mp3Arr objectAtIndex:indexMp3];
        mp3F = [self soudFileSpeedCheck:mp3F];
        mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
        if([[TLSoundPlayer shareSingle] isFilePlaying:mp3F]){
            self.isAutoRead = YES;
            [self cleanStatusForCurrentSreadBtn];
            self.SreadIndex = nil;
            [self.soundBtn setButtonStatus:StatusButton_3_View_Status_work];
            [self.fview unShow];
            [readView updatePagesSreadBtnToShow:NO];
        }
    }else{
        self.isAutoRead = NO;
        [self reflashFloatViewShow];
        [readView updatePagesSreadBtnToShow:YES];
    }
}

#pragma mark- 后台播放相关
- (void)stopButtonAction:(UIButton *)sender {
}

//播放/暂停
- (void)playOrPauseMusicButtonAction:(UIButton *)sender {
    static  NSInteger pauseIndexMp3 = -1;
    if (self.isAutoRead && !self.isAutoRead_ForRec) {
        //暂停
        NSInteger index = indexMp3;
        if (mp3Arr.count > index && index >= 0 && pauseIndexMp3 == -1) {
            NSString* mp3F = [mp3Arr objectAtIndex:index];
            mp3F = [self soudFileSpeedCheck:mp3F];
            mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
            AVAudioPlayer* player = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:mp3F];
            if (player.isPlaying) {
                [player pause];
                pauseIndexMp3 = index;
            }
        }
        //恢复
        else if(pauseIndexMp3 >=0) {
            NSInteger index = pauseIndexMp3;
            NSString* mp3F = [mp3Arr objectAtIndex:index];
            mp3F = [self soudFileSpeedCheck:mp3F];
            mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
            AVAudioPlayer* player = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:mp3F];
            if (!player.isPlaying) {
                [player play];
                indexMp3 = index;
            }
            pauseIndexMp3 = -1;
        }
    }
    //封面支持打开播放
    if (self.hasHang && !self.isAutoRead && !self.isAutoRead_ForRec) {
        //停止
        [[TLSoundPlayer shareSingle] stopAllFiles];
        //
        self.isAutoRead = YES;
        [self indexMp3_Zero];
        pauseIndexMp3 = indexMp3;
        [self checkNextPage_ForNoMp3];
        if (self.isAutoRead && mp3Arr.count >0){
            [self performSelector:@selector(playBookSound) withObject:nil afterDelay:0.01];
        }
        [self.fview unShow];
        [readView updatePagesSreadBtnToShow:NO];
    }
}

//上一首
- (void)previousMusicButtonAction:(UIButton *)sender {
    [self stopButtonAction:sender];
    
    //设置数据为播放数据
    if (self.isAutoRead) {
        [readView prevPage];
    }
    
    //刷新界面显示
    [self refreshUI_backGround_Player];
}

//下一首
- (void)nextMusicButtonAction:(UIButton *)sender {
    [self stopButtonAction:sender];
    
    //设置数据为播放数据
    if (self.isAutoRead) {
        [readView nextPage];
    }
    
    //刷新界面显示
    [self refreshUI_backGround_Player];
}

//刷新界面显示
static NSMutableDictionary* _songInfo;
- (void)refreshUI_backGround_Player {
    //后台运行才需要更新
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        //获取播放数据
        UIImage *image = self.coverImg;
        
        _songInfo = [NSMutableDictionary new];
        MPMediaItemArtwork *albumArt = nil;
        if (image) {
            albumArt = [[MPMediaItemArtwork alloc] initWithImage:image];
        }
        [_songInfo setObject:self.bookName forKey:MPMediaItemPropertyTitle];
        [_songInfo setObject:@"" forKey:MPMediaItemPropertyAlbumTitle];
        [_songInfo setObject:@"" forKey:MPMediaItemPropertyArtist];
        if(albumArt)[_songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
        
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:_songInfo];
    }
}

//刷新后台进度
- (void)updateProgress:(NSTimer *)updatedTimer {
    
    //获取播放器
    NSInteger index = indexMp3;
    if (mp3Arr.count > index && index >= 0) {
        NSString* mp3F = [mp3Arr objectAtIndex:index];
        mp3F = [self soudFileSpeedCheck:mp3F];
        mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
        AVAudioPlayer* audioPlayer = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:mp3F];
        double progress = audioPlayer.currentTime;
        double duration = audioPlayer.duration;
//        if ((int)progress >= (int)duration - 0.1) {
//            if (indexMp3 >= mp3Arr.count-1) {
//                [readView nextPage];
//            }
//        }
        
        //后台运行才需要更新
        if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
            //音乐当前已经播放时间
            [_songInfo setObject:[NSNumber numberWithDouble:progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
            //歌曲剩余时间设置
            [_songInfo setObject:[NSNumber numberWithDouble:duration] forKey:MPMediaItemPropertyPlaybackDuration];
            
            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:_songInfo];
        }
        
    }
}

/**
 *  开始计时器
 */
- (void)start_backPlayTimer {
    if (!self.backPlayTimer && self.hasHang) {
        self.backPlayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];
    }
}

#pragma mark - 耳机控制/系统界面控制

- (void)viewDidAppear_floatBtns:(BOOL)animated {
    [self viewDidAppear_floatBtns:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

- (void)viewWillDisappear_floatBtns:(BOOL)animated {
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
    [self viewWillDisappear_floatBtns:animated];
}

- (BOOL)canBecomeFirstResponder {
    return self.hasHang;
}

//received remote event
-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
    //type==2  subtype==单击暂停键：103，双击暂停键104
    if (event.type == UIEventTypeRemoteControl) {
        switch (event.subtype) {
                
            case UIEventSubtypeRemoteControlPlay:{
                //NSLog(@"play---------");
                [self playOrPauseMusicButtonAction:nil];
            }break;
            case UIEventSubtypeRemoteControlPause:{
                //NSLog(@"Pause---------");
                [self playOrPauseMusicButtonAction:nil];
            }break;
            case UIEventSubtypeRemoteControlStop:{
                //NSLog(@"Stop---------");
                [self stopButtonAction:nil];
            }break;
            case UIEventSubtypeRemoteControlTogglePlayPause:{
                //单击暂停键：103
                //NSLog(@"单击暂停键：103");
                [self playOrPauseMusicButtonAction:nil];
            }break;
            case UIEventSubtypeRemoteControlNextTrack:{
                //双击暂停键：104
                //NSLog(@"双击暂停键：104");
                [self nextMusicButtonAction:nil];
            }break;
            case UIEventSubtypeRemoteControlPreviousTrack:{
                //NSLog(@"三击暂停键：105");
                [self previousMusicButtonAction:nil];
            }break;
            case UIEventSubtypeRemoteControlBeginSeekingForward:{
                //NSLog(@"单击，再按下不放：108");
            }break;
            case UIEventSubtypeRemoteControlEndSeekingForward:{
                //NSLog(@"单击，再按下不放，松开时：109");
            }break;
            default:
                break;
        }
    }
}

#pragma mark- 处理来电
- (void)pausePlaying:(BOOL)isResume
{
    static  NSInteger pauseIndexMp3 = -1;
    if (self.isAutoRead && !self.isAutoRead_ForRec) {
        //暂停
        NSInteger index = indexMp3;
        if (mp3Arr.count > index && index >= 0 && !isResume) {
            NSString* mp3F = [mp3Arr objectAtIndex:index];
            mp3F = [self soudFileSpeedCheck:mp3F];
            mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
            AVAudioPlayer* player = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:mp3F];
            if (player.isPlaying) {
                [player pause];
                pauseIndexMp3 = index;
            }
        }
        //恢复
        else if(pauseIndexMp3 >=0 && isResume) {
            NSInteger index = pauseIndexMp3;
            NSString* mp3F = [mp3Arr objectAtIndex:index];
            mp3F = [self soudFileSpeedCheck:mp3F];
            mp3F = [DataProcessing bookPathForBookID:self.bookid subDir:mp3F];
            AVAudioPlayer* player = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:mp3F];
            if (!player.isPlaying) {
                [player play];
                indexMp3 = index;
                pauseIndexMp3 = -1;
            }
        }
    }
}

- (void)toListenner_Call
{
    AudioSessionInitialize(NULL, NULL, interruptionListenner, (__bridge void*)self);
}

void interruptionListenner(void* inClientData, UInt32 inInterruptionState)
{
    ReadBookVOrH_VC* pTHIS = [ReadBookVOrH_VC currentReadInstance];
    if (pTHIS) {
        //NSLog(@"interruptionListenner %lu", inInterruptionState);
        if (kAudioSessionBeginInterruption == inInterruptionState) {
            //NSLog(@"Begin interruption");
            [pTHIS.self pausePlaying:NO];
        }
        else
        {
            //NSLog(@"Begin end interruption");
            [pTHIS.self pausePlaying:YES];
            //NSLog(@"End end interruption");
        }
        
    }
}

#pragma mark-

@end
